package gaetest.server;

import gaetest.domain.EMF;
import gaetest.domain.User;

import java.util.logging.Logger;

import javax.persistence.EntityManager;
import javax.persistence.EntityTransaction;


import com.google.web.bindery.requestfactory.shared.Locator;

public class UserLocator extends Locator<User, Long> {
  private static Logger logger = Logger.getLogger(UserLocator.class.getName());

  /* Temporary comment Database Manager (EMF) to test just GWT RequestFactory. */

  // private static EntityManager em = EMF.get().createEntityManager();

  @Override
  public User create(Class<? extends User> clazz) {
    try {
      return clazz.newInstance();
    } catch (InstantiationException e) {
      throw new RuntimeException(e);
    } catch (IllegalAccessException e) {
      throw new RuntimeException(e);
    }
  }

  public void delete(User usr) {
    // em.remove(usr);
  }

  @Override
  public User find(Class<? extends User> clazz, Long id) {
    return new User();
    // return em.find(clazz, id);
  }

  public User find(Long id) {
    return find(getDomainType(), id);
  }

  @Override
  public Class<User> getDomainType() {
    return User.class;
  }

  @Override
  public Long getId(User domainObject) {
    return domainObject.getId();
  }

  @Override
  public Class<Long> getIdType() {
    return Long.class;
  }

  @Override
  public Object getVersion(User domainObject) {
    return domainObject.getVersion();
  }

  public Long save(User usr) {
    logger.info("Saving user: [" + usr.getName() + "]");
    // EntityManager em = EMF.get().createEntityManager();
    // try {
    // em.getTransaction().begin();
    // em.persist(post);
    // em.getTransaction().commit();
    // } finally {
    // em.close();
    // }
    EntityManager em = EMF.get().createEntityManager();
    EntityTransaction tx = em.getTransaction();
    try {
      tx.begin();
      em.persist(usr);
      em.getTransaction().commit();
    } catch (Exception e) {
      logger.warning("Rolling Back: " + e.toString());
      tx.rollback();
    } finally {
      em.close();
    }
    logger.info("Exiting createContact");

    return usr.getId();
  }

}
